package dao;

import util.Config;

import java.sql.*;
import java.util.HashMap;
import java.util.LinkedList;

/**
 * PackageName: dao
 * ClassName: BaseDao
 * Author: tum0r
 * Time: 2020/5/24 16:00
 */
abstract public class BaseDao {
    private Connection connection;
    private PreparedStatement statement;
    private ResultSet resultSet;

    public boolean open(String path) throws ClassNotFoundException, SQLException {
        Class.forName(Config.SQL_DRIVER);
        connection = DriverManager.getConnection(Config.SQL_URL + path);
        if (connection == null) {
            return false;
        }
        connection.setAutoCommit(false);
        init();
        return true;
    }

    private void setParameter(String command, Object... parameter) throws SQLException {
        statement = connection.prepareStatement(command);
        if (parameter != null && parameter.length != 0) {
            for (int i = 0; i < parameter.length; i++) {
                statement.setObject(i + 1, parameter[i]);
            }
        }
    }

    public LinkedList<LinkedList<Object>> query(String command, Object... parameter) throws SQLException {
        LinkedList<LinkedList<Object>> result = new LinkedList<>();
        LinkedList<Object> item;
        setParameter(command, parameter);
        resultSet = statement.executeQuery();
        while (resultSet.next()) {
            int column = resultSet.getMetaData().getColumnCount();
            item = new LinkedList<>();
            for (int i = 1; i <= column; i++) {
                item.add(resultSet.getObject(i));
            }
            result.add(item);
        }
        return result;
    }

    public int update(String command, Object... parameter) throws SQLException {
        setParameter(command, parameter);
        return statement.executeUpdate();
    }

    public void init() throws SQLException {
        update(Config.CREATE_FILE_INFORMATION_TABLE);
        update(Config.CREATE_FILE_CONTENT_TABLE);
    }

    public void commit() throws SQLException {
        if (connection != null && !connection.isClosed()) {
            connection.commit();
        }
    }

    public void rollback() throws SQLException {
        if (connection != null && !connection.isClosed()) {
            connection.rollback();
        }
    }

    public void close() throws SQLException {
        if (resultSet != null && !resultSet.isClosed()) {
            resultSet.close();
            resultSet = null;
        }
        if (statement != null && !statement.isClosed()) {
            statement.close();
            statement = null;
        }
        if (connection != null && !connection.isClosed()) {
            connection.close();
            connection = null;
        }
    }
}
